﻿using System;
using _5E.Infrastructure.Collections;
using _5E.Infrastructure.Logging;
using Newtonsoft.Json;
using StoneAge.Contract;
using StoneAge.Controller.Request;
using StoneAge.Controller.Routing;
using StoneAge.DataContract.Messaging;
using StoneAge.Models.Entity;

namespace StoneAge.Controller.Handlers
{
    class CreateRoleHandler : PostResponseRequestHandler
    {
        private IRoleService m_roleService = null;

        public CreateRoleHandler(IRoleService roleService)
            : base(Routes.CREATE_ROLE)
        {
            m_roleService = roleService;
        }

        protected override ResponseBase GetResponseBy(WebRequest webRequest)
        {
            CreateRoleResponse response;
            try
            {
                CreateRoleRequest request = new CreateRoleRequest();
                request.Role = JsonConvert.DeserializeObject<Role>(webRequest.QueryArguments.ExtractFor<string>("role"));
                request.Role.AccountId = webRequest.User.AccountId;
                request.BirthMapId = webRequest.QueryArguments.ExtractFor<Int32>("mapId");
                response = m_roleService.CreateBy(request);
                if (response.Success)
                {
                    webRequest.User.RoleId = response.RoleId;
                    webRequest.User.Save();
                }
            }
            catch (Exception ex)
            {
                LoggingFactory.Logger.Log(ex);
                response = new CreateRoleResponse { Success = false };
            }
            return response;
        }
    }
}
